<template>
  <div class="goodCard">
    <h4>我的购物车（{{ goodsList.length }}）</h4>

    <p v-show="show" class="toast">您的购物车暂无商品，快去购物吧</p>

    <div class="cardList">
      <ul>
        <li v-for="(item, index) in goodsList" :key="index">
          <van-swipe-cell>
           
            <van-row align="center">
              <van-col span="2">
                <van-checkbox
                  v-model="item.checked"
                  checked-color="#ee0a24"
                ></van-checkbox>
              </van-col>

              <van-col span="22">
                <van-card
                  :price="item.s_good.price+'.00'"
                  :desc="item.s_good.desc"
                  :title="item.s_good.name"
                  :thumb="item.s_good.s_goods_photos[0].path"
                  :origin-price="item.s_good.sale_price+'.00'"
                  @click="jumpToGoods(item.s_good.id)"
                >
                  <template #tags>
                    <van-tag plain type="danger">包邮</van-tag>
                  </template>
                </van-card>
              </van-col>
            </van-row>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="deleteGoodsData(item.id)"
              />
            </template>
          <van-stepper
            v-model="item.num"
            class="count"
            @change="deleteGoods(item)"
            min="0"
            input-width="5vw"
            button-size="5vw"
          />
          
          </van-swipe-cell>
        </li>
      </ul>
    </div>

    <div class="sendOrder">
      <van-checkbox v-model="allchecked" checked-color="#ee0a24"
        ><span>全选</span></van-checkbox
      >

      <div class="right">
        <div class="choose">
          <p>
            已选 <span style="color: red">{{ chooseNum }}</span
            >件
          </p>
          <span
            >合计￥ <span style="color: red">{{ choosePrice }}</span></span
          >
        </div>
        <van-button
          type="danger"
          text="结算"
          class="submitButton"
          round
          @click="send"
        />
      </div>
    </div>
    <doucker :choossIndex="1" />
  </div>
</template>
<script>
document.documentElement.scrollTop = 0;
</script>
<script setup>
import { onBeforeMount, ref, computed, watch,toRaw } from "vue";
import { put, get, getData, deleteService } from "../../utils/request.js";
import doucker from "../../components/doucker.vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const show = ref(false);
const store = useStore();
const goodsList = ref([]);
const active = ref(0);
const titleList = ref(["全部", "待付款", "代发货", "代发货", "待评价"]);
let timer;
const getGoodsData = async () => {
  Toast.loading({
    message: "正在请求购物车数据，请稍后...",
    forbidClick: true,
    duration: 0,
  });

  const data = {
    project_id: 234,
  };
  let result;
  try {
    result = await getData("/shoppingCart", data);
  } catch (error) {
    timer = setTimeout(() => {
      Toast.clear();
      Toast.fail({ message: "请求失败，请刷新本页面", forbidClick: true });
      clearTimeout(timer);
    }, 3000);
  }
  if (result.status == 200) {
    Toast.clear();

    goodsList.value = result.data.result;
    if (goodsList.value.length == 0) {
      show.value = true;
    } else {
      goodsList.value.forEach((ele, index) => {
        ele.checked = true;
      });
    }
  }
};
getGoodsData();
const updateGoods = async (data) => {
  const gooodData = {
    num: data.num,
  };
  console.log(gooodData,data.id);
  let result=[];
  try {
    console.log(111111);
    result = await put(`/shoppingCart/${data.id}`, gooodData);
    console.log(result);
    
  } catch (error) {
    
  }
   
  
};
//获取选中项
const allchecked = computed({
  get: () => {
    return goodsList.value.every((ele) => ele.checked);
  },
  set: (param) => {
    goodsList.value.forEach((ele, index) => {
      ele.checked = param;
    });
  },
});
//已选择商品数量
const chooseNum = computed(() => {
  let arr = goodsList.value.filter((ele) => {
    return ele.checked;
  });
  return arr.length;
});
//已选择商品价格
const choosePrice = computed(() => {
  let price = 0;
  goodsList.value.forEach((ele) => {
    price += Number(ele.s_good.sale_price) * Number(ele.num);
  });
  return price;
});
//删除购物车
const deleteGoodsData = async (id) => {
  let result;
  // Toast.loading({
  //   message: "正在删除，请稍后...",
  //   forbidClick: true,
  //   duration: 0,
  // });

  try {
    result = await deleteService(`/shoppingCart/${id}`);
  } catch (error) {
    console.log(error);
    Toast.clear()
    Toast.fail({ message: "删除失败，请稍后再尝试", forbidClick: true });
  }
  if (result.status == 200) {
    // searchList.value = result.data.result.rows;
    getGoodsData();
  }
};
//每更改一次 就将数据上传到后台
const deleteGoods = (item) => {
  if (item.num == 0) {
    deleteGoodsData(item.id);
  }
  console.log(goodsList.value);
  goodsList.value.forEach((ele)=>{
    let data={
      id:ele.id,
      num:ele.num
    }

   updateGoods(data)
  })
 
  
};
onBeforeMount(() => {
  Toast.clear();
  clearTimeout(timer);
});
const send = () => {
  let arr = goodsList.value.filter((ele) => {
    return ele.checked;
  });
  if (arr.length == 0) {
    Toast.fail({ message: "请勾选您所需要的商品", forbidClick: true });
  } else {
    store.commit("order/setgoodsOrder", arr);
    router.push(`/addOrder/${0}`);
  }
};
const jumpToGoods = (id) => {
  console.log(id);
  router.push(`/goodsDetail/${id}`);
};

watch(
  () => route.path,
  (newPath, oldPath) => {
    getGoodsData();
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.goodCard {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background-color: #f7f8fa;

  .toast {
    color: #333333;
    margin: 10vh;
    text-align: center;
  }
  h4 {
    text-align: center;

    font-size: 4.2vw;
    color: #333333;
  }
  .cardList {
    width: 100%;
    padding-bottom: 15vh;
    ul {
      width: 95%;
      margin: 0 auto;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #f7f8fa;
      border-radius: 15px;
      li {
        width: 100%;

        background-color: white;
        position: relative;
        margin-bottom: 1vh;
        // display: flex;
        // align-items: center;
        border-radius: 10px;
        .showMore {
          word-break: break-all;
          width: 100%;
        }
        .count {
          position: relative;
          top: -2vh;
          // z-index: 10;
          left: 75vw;
        }
        .van-card {
          box-sizing: border-box;
          margin: 0;
        
          border-left: 1px solid white;
          margin-left: -2.06vw;
          --van-card-background-color: white;
            transform: translateY(1.5vh);
        }
      }
    }
    ul > li:nth-child(1) {
      // margin-top:3vh ;
    }
  }
  .sendOrder {
    position: fixed;
    display: flex;
    justify-content: space-between;
    padding: 0 3vw;
    width: 100%;
    bottom: 6.5vh;
    background-color: white;
    .submitButton {
      width: 30vw;
      margin-right: 6vw;
      --van-button-default-background-color: black;
    }
    .right {
      display: flex;
      align-items: center;
      --van-button-default-background-color: #1989fa;
      .choose {
        font-size: 14px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        text-align: center;
        p {
          margin: 0;
        }
      }
    }
  }
}
.delete-button{
  height: 100%;
}
</style>
